<?php

namespace app\common\service;

use app\common\model\AdminPower;
use app\common\model\AdminMenu;
use app\common\model\AdminUser;
use app\common\model\AdminPowerField;
use app\common\model\AdminPowerTable;
use app\common\model\AdminTenant;
use app\common\model\AdminTenantProduct;
use think\facade\Request;
use think\facade\Cache;

class Power
{
    /*=====数据查看、修改、删除where验证权限开始=====*/
    public function IndexWhere($node = '')
    {
        $login_source = GetToken('login_source') ?: 'admin';//分为admin和user
        $where = '';
        if (!empty(GetToken('tenant_id'))) {
            $where = " and a.tenant_id='" . GetToken('tenant_id') . "'";
        }
        if (GetToken('is_super') == 1) {
            return $where;
        }
        $AdminPowerTable = new AdminPowerTable();
        $Table = $AdminPowerTable->where("power_node='" . $node . "' and status=1 and is_delete=0")->field("power_user,power_role,power_department,power_field")->findOrEmpty()->toArray();
        if (empty($Table)) {
            return $where;
        }
        $power_field = !empty($Table['power_field']) ? json_decode($Table['power_field'], true) : [];
        $path_ids = GetToken('id');
        $copy = "[" . $path_ids . "]";
        $tWhere = "";
        if ($power_field) {
            if ($login_source == 'admin') {
                $AdminUser = new AdminUser();
                $User = $AdminUser->where("path_id='" . GetToken('id') . "'")->field("id")->select()->toArray();
                foreach ($User as $k => $v) {
                    if (strpos($copy, '[' . $v['id'] . ']') !== false) {
                    } else {
                        $path_ids .= ',' . $v['id'];
                        $copy .= "[" . $v['id'] . "]";
                    }
                }
            }
            foreach ($power_field as $k => $v) {
                $is_path = !empty($v['is_path']) ? $v['is_path'] : 2;
                $ex = ' or ';
                if ($k == 0) {
                    $ex = '';
                }
                $t = explode('__', $v['field']);
                if (count($t) == 2) {
                    $field = $t[0] . "." . $t[1];
                } else {
                    $field = "a." . $v['field'];
                }
                if ($is_path == 1) {
                    $tWhere .= $ex . $field . " in (" . $path_ids . ")";
                } else {
                    $tWhere .= $ex . $field . "='" . GetToken('id') . "'";
                }
            }
        }
        if ($login_source == 'admin') {
            $power = 2;
            if ($Table['power_user']) {
                $power = $this->SearchPower(GetToken('id'), $Table['power_user']);
            }
            if ($Table['power_role'] && $power == 2) {
                $power = $this->SearchPower(GetToken('role_ids'), $Table['power_role']);
            }
            if ($Table['power_department'] && $power == 2) {
                $power = $this->SearchPower(GetToken('department_ids'), $Table['power_department']);
            }
            if ($power == 2 && $tWhere) {
                if (count($power_field) == 1) {
                    $where .= " and " . $tWhere;
                } else {
                    $where .= " and (" . $tWhere . ")";
                }

            }
        }
        return $where;
    }
    /*=====数据查看、修改、删除where验证权限结束=====*/

    /*=====列表数据字段显示权限开始=====*/
    public function IndexField($field = '', $node = '')
    {

        $login_source = GetToken('login_source') ?: 'admin';//分为admin和user
        if ($login_source != 'admin' || GetToken('is_super') == 1) {
            return $field;
        }
        $AdminPowerField = new AdminPowerField();
        $PowerField = $AdminPowerField->where("status=1 and power_node='" . $node . "' and is_delete=0")->field('power_field')->findOrEmpty()->toArray();
        $rule = !empty($PowerField['power_field']) ? json_decode($PowerField['power_field'], true) : [];
        if ($rule) {
            $ruleData = [];
            foreach ($rule as $k => $v) {
                $typeArr = explode(',', $v['type']);
                $fieldArr = explode(',', $v['field']);
                foreach ($typeArr as $k2 => $v2) {
                    foreach ($fieldArr as $k3 => $v3) {
                        $ruleData[$v2][$v3] = $v;
                    }
                }
            }
            $fields = explode(',', $field);
            foreach ($fields as $k => $v) {
                $t = explode('.', $v);
                $rule_field = $t[1];
                if ($t[0] != 'a') {
                    $f = explode('as', $t[1]);
                    $rule_field = trim($f[1]);
                }
                if (!empty($ruleData['detail'][$rule_field])) {
                    $power = $this->PowerFormField($ruleData['detail'][$rule_field]);
                    if ($power == 1) {
                        unset($fields[$k]);
                    }
                }
            }
            $field = '';
            foreach ($fields as $k => $v) {
                $field .= $v . ',';
            }
            $field = rtrim($field, ",");
        }
        return $field;
    }


    /*表单字段权限:查看、修改、新增*/
    public function FormField($item = [], $node = '', $type = 'detail', $postnode = 'detail')
    {

        $login_source = GetToken('login_source') ?: 'admin';//分为admin和user
        $token_id = GetToken('id') ?: 0;
        $token_time = date('Y-m-d H:i:s');
        if ($type == 'add' || $type == 'edit') {
            foreach ($item as $k => $v) {
                if ($type == 'add') {
                    $item[$k]['create_id'] = $token_id;
                    $item[$k]['create_time'] = $token_time;
                }
                $item[$k]['update_id'] = $token_id;
                $item[$k]['update_time'] = $token_time;
            }
        }
        $data['detail'] = $item;
        $data['power'] = [];
        if ($login_source != 'admin') {
            if ($type == 'add' || $type == 'edit') {
                return $item;
            }
            return $data;
        }

        $AdminPowerField = new AdminPowerField();
        $where = "status=1 and power_node='" . $node . "' and is_delete=0";
        $PowerField = $AdminPowerField->where($where)->field('power_field')->findOrEmpty()->toArray();
        $rule = !empty($PowerField['power_field']) ? json_decode($PowerField['power_field'], true) : [];
        if (empty($rule)) {
            if ($type == 'add' || $type == 'edit') {
                return $item;
            }
            return $data;
        }
        $ruleData = [];
        foreach ($rule as $k => $v) {
            $typeArr = explode(',', $v['type']);
            $fieldArr = explode(',', $v['field']);
            foreach ($typeArr as $k2 => $v2) {
                foreach ($fieldArr as $k3 => $v3) {
                    $ruleData[$v2][$v3] = $v;
                }
            }
        }

        switch ($type) {
            case "detail":
                $postnode = !empty($postnode) ? $postnode : 'detail';
                $list = !empty($ruleData[$postnode]) ? $ruleData[$postnode] : [];
                foreach ($list as $k => $v) {
                    $power = $this->PowerFormField($v);
                    if ($power == 1) {
                        $data['power'][$k] = 1;
                        if ($postnode == 'detail') {
                            $data['detail'][$k] = '';
                        }
                    }
                }
                if ($postnode == 'edit') {
                    $list = !empty($ruleData['detail']) ? $ruleData['detail'] : [];
                    foreach ($list as $k => $v) {
                        $power = $this->PowerFormField($v);
                        if ($power == 1) {
                            $data['power'][$k] = 1;
                            $data['detail'][$k] = '';
                        }
                    }
                }
                break;
            case "add":
            case "edit":
                $data = $item;
                $list = !empty($ruleData[$type]) ? $ruleData[$type] : [];
                foreach ($list as $k => $v) {
                    $power = $this->PowerFormField($v);
                    if ($power == 1) {
                        $t = explode("__", $k);
                        $table = "a";
                        $field = $k;
                        if (count($t) == 2) {
                            $table = $t[0];
                            $field = $t[1];
                        }
                        if (isset($data[$table][$field])) {
                            unset($data[$table][$field]);
                        }
                    }
                }
                break;
        }
        return $data;
    }

    public function PowerFormField($data)
    {

        if (empty($data['power_user']) && empty($data['power_role']) && empty($data['power_department'])) {
            return 1;
        }
        $ids = !empty($data['power_user']) ? $data['power_user'] : '';
        $power = $this->SearchPower(GetToken('id'), $ids);
        if ($power == 2) {
            $ids = !empty($data['power_role']) ? $data['power_role'] : '';
            $power = $this->SearchPower(GetToken('role_ids'), $ids);
        }
        if ($power == 2) {
            $ids = !empty($data['power_department']) ? $data['power_department'] : '';
            $power = $this->SearchPower(GetToken('department_ids'), $ids);
        }
        return $power;
    }


    /*查询匹配权限*/
    public function SearchPower($id = '', $ids = '')
    {
        $idsArr = explode(',', $ids);
        $idArr = explode(',', $id);
        $power = 2;
        foreach ($idsArr as $k => $v) {
            foreach ($idArr as $k2 => $v2) {
                if ($v2 == $v) {
                    $power = 1;
                }
            }
        }
        return $power;
    }


    /*=====事件节点及页面访问权限开始=====*/
    public function Node()
    {
        if (GetToken('is_super') == 1) {
            return 1;
        }
        $power = 2;
        $app = strtolower(app('http')->getName());
        $controller = strtolower(Request::controller());
        $action = strtolower(Request::action());
        if ($action == 'update_field') {
            $action = "edit";
        }
        if ($action == 'template_excel') {
            $action = "import_excel";
        }
        if ($action == 'detail') {
            $action = input("node") ?: 'detail';
        }
        if ($action == 'tabsum') {
            $action = 'index';
        }



        $rule = '/' . $app . '/' . $controller . '/' . $action . '/';
        $power_node = $app . ':' . $controller . ':' . $action;
        $nodes = $this->GetAllNode();
        $lists = $nodes['button'];
        foreach ($lists as $k => $v) {
            if ($v == $power_node) {
                $power = 1;
            }
        }
        if ($power == 2) {
            $lists = $nodes['menu'];
            foreach ($lists as $k => $v) {
                $href = explode(strtolower($rule), strtolower($v['href']));
                if (count($href) >= 2) {
                    $power = 1;
                }
            }
        }
        return $power;
    }

    /*获取所有菜单及按钮*/
    public function GetAllNode()
    {
        $CacheId = 'all_node_' . GetToken('id');
        $data = Cache::get($CacheId);
        if (!empty($data)) {
            return $data;
        }
        $AdminMenu = new AdminMenu();
        $field = "id,title,icon,href,open_type as openType,parent_id,type,power_node";
        $where = "status=1 and is_delete=0";
        $check = 1;
        if (GetToken('is_super') == 1 && empty(GetToken('tenant_id'))) {
            $check = 2;
        }
        if ($check == 1) {
            $user = $this->AllNodePower(GetToken('id'), 'user');
            $role = $this->AllNodePower(GetToken('role_ids'), 'role');
            $department = $this->AllNodePower(GetToken('department_ids'), 'department');
            $menuIds = '';
            if ($user) {
                $menuIds .= $user . ',';
            }
            if ($role) {
                $menuIds .= $role . ',';
            }
            if ($department) {
                $menuIds .= $department . ',';
            }
            $Ids = rtrim($menuIds, ",");
            if (empty($Ids)) {
                $data['menu'] = [];
                $data['button'] = [];
                Cache::set($CacheId, $data, 86400);
                return $data;
            }
            $copy = [];
            if (!empty(GetToken('tenant_id')) && GetToken('is_super') == 1) {
                $AdminTenant = new AdminTenant();
                $Tenant = $AdminTenant->where("id='" . GetToken('tenant_id') . "' and is_delete=0 and status=1")->field("product_ids")->findOrEmpty()->toArray();
                if (!empty($Tenant['product_ids'])) {
                    $AdminTenantProduct = new AdminTenantProduct();
                    $Product = $AdminTenantProduct->where("id in(" . $Tenant['product_ids'] . ")")->field("menu_ids")->select()->toArray();
                    $Ids = '';
                    foreach ($Product as $k => $v) {
                        $Ids .= $v['menu_ids'] . ',';
                    }
                }
            }
            $arrId = explode(',', $Ids);
            $mendId = '';
            foreach ($arrId as $k => $v) {
                if (empty($copy['id_' . $v])) {
                    $mendId .= $v . ',';
                    $copy['id_' . $v] = $v;
                }
            }
            if (empty($mendId)) {
                $mendId = '999999999999';
            }
            $where .= " AND id IN(" . rtrim($mendId, ",") . ")";
        }
        $menu = $AdminMenu->where($where)->field($field)->orderRaw("sort asc,id desc")->select()->toArray();
        $allMenu = [];
        $allButton = [];
        foreach ($menu as $k => $v) {
            $icon = !empty($menu[$k]['icon']) ? $menu[$k]['icon'] : 'icon-danxuankuang';
            $menu[$k]['icon'] = 'ruinuo-icon ' . $icon;
            if ($v['type'] == 3) {
                if ($v['power_node']) {
                    $allButton[] = $v['power_node'];
                }
            } else {
                $allMenu[] = $menu[$k];
                if ($v['power_node']) {
                    $allButton[] = $v['power_node'];
                }
            }
        }
        $data['menu'] = $allMenu;
        $data['button'] = $allButton;
        Cache::set($CacheId, $data, 86400);
        return $data;
    }


    /*获取所有菜单及按钮的权限*/
    public function AllNodePower($value = '', $num = '')
    {
        $powerId = '';
        if ($value) {
            $AdminPower = new AdminPower();
            $tenant_id = GetToken('tenant_id') ?: 0;
            $powerWhere = "tenant_id='" . $tenant_id . "' and mark='" . $num . "' and cat='menu' and is_delete=0 and mark_id IN(" . $value . ")";
            $userPower = $AdminPower->where($powerWhere)->field("cat_ids")->select()->toArray();
            foreach ($userPower as $k => $v) {
                $powerId .= rtrim($v['cat_ids'], ",") . ',';
            }
            $powerId = rtrim($powerId, ",");
        }
        return $powerId;
    }
    /*=====事件节点及页面访问权限结束=====*/


}